package org.fuckerfucker.urmomboot1.controller;

import org.fuckerfucker.urmomboot1.service.FileUploadService;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@Controller
public class FileController {

    private final FileUploadService uploadService;

    public FileController(FileUploadService uploadService) {
        this.uploadService = uploadService;
    }

    enum TemplateEnpoint {
        // upload.html
        upload,
        // status.html
        status 
    }

    // 上传页面
    @GetMapping("/")
    public String uploadForm() {
        return TemplateEnpoint.upload.name();
    }

    // 处理上传api
    @PostMapping("/upload")
    public String handleUpload(
            @RequestParam("file") MultipartFile file,
            RedirectAttributes redirectAttributes) {
        try {
            String message = uploadService.uploadFile(file);
            redirectAttributes.addFlashAttribute("message", message);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", "上传失败：" + e.getMessage());
        }
        return "redirect:/" + TemplateEnpoint.status.name() ;
    }

    // 上传状态页
    @GetMapping("/status")
    public String uploadStatus(Model model) {
        // 确保状态页能获取到消息
        if (!model.containsAttribute("message")) {
            model.addAttribute("message", "请上传文件");
        }
        return TemplateEnpoint.status.name();
    }
}
    